<?php
/* --------------------------------------------------------------
   FetchShopConfigAction.php 2024-05-22
   Gambio GmbH
   http://www.gambio.de
   Copyright (c) 2024 Gambio GmbH
   Released under the GNU General Public License (Version 2)
   [http://www.gnu.org/licenses/gpl-2.0.html]
   --------------------------------------------------------------
*/

declare(strict_types=1);

namespace Gambio\Api\Modules\ShopConfig\App\Actions;

use Gambio\Core\Application\Http\Request;
use Gambio\Core\Application\Http\Response;
use Gambio\Core\Configuration\Services\ConfigurationService;
use Gambio\Api\Modules\ShopConfig\App\ShopConfigApiRequestValidator;

/**
 * Class FetchShopConfigAction
 *
 * @package Gambio\Api\Modules\ShopConfig\App\Actions
 */
class FetchShopConfigAction
{
    
    protected ConfigurationService          $configurationService;
    protected ShopConfigApiRequestValidator $requestValidator;
    
    
    /**
     * FetchShopConfigAction constructor.
     *
     * @param ConfigurationService          $configurationService
     * @param ShopConfigApiRequestValidator $requestValidator
     */
    public function __construct(
        ConfigurationService          $configurationService,
        ShopConfigApiRequestValidator $requestValidator
    ) {
        $this->configurationService = $configurationService;
        $this->requestValidator     = $requestValidator;
    }
    
    
    /**
     * @param Request  $request
     * @param Response $response
     * @param array    $args
     *
     * @return Response
     */
    public function __invoke(Request $request, Response $response, array $args): Response
    {
        $allowedKeys = $this->requestValidator->getAllowedConfigKeys();
        $prefix      = $this->requestValidator->getConfigPrefix();
        
        $data = [];
        foreach ($allowedKeys as $key) {
            $config = $this->configurationService->find($prefix . $key);
            $data[] = [
                "key"   => $key,
                "value" => $config?->value(),
            ];
        }
        
        return $response->withJson(["data" => $data]);
    }
    
}